package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.dto.SendSmsDto;
import cn.itsource.basic.exception.CustomException;
import cn.itsource.basic.service.IVerifyCodeService;
import cn.itsource.basic.util.SendSmsUtil;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.basic.util.VerifyCodeUtils;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Object imageCode(String key) {
        String code = StrUtils.getComplexRandomString(4);//生成4位随机数
        //存储Redis 使用前端传来的key作为Redis的key
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        //根据code生成 base64 转码后的图片
        String base64 = VerifyCodeUtils.VerifyCode(110, 38, code);
        return base64;
    }

    /**
     * 短信验证码
     */
    @Override
    public void sendSmsCode(SendSmsDto dto) {
//        1. 空参数校验
        if(StringUtils.isEmpty(dto.getMobile())){
            throw new CustomException("请输入手机号码");
        }
//        2. 判断该手机号用户是否已经注册
        User user = userMapper.queryByUserName(dto.getMobile());
        if(user != null){
            throw new CustomException("该用户已经注册");
        }
//        3. 根据前端传递过来的图片验证码的key（UUID），去redis中获取验证码字串
        Object imageCode = redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if(imageCode == null){
            //        1. 获取不到，返回自定义异常，图片验证码失效
            throw new CustomException("图片验证码已过期");
        }
//        4. 判断前端填写的图片验证码与redis中获取的是否一致 equalsIgnoreCase-代表不区分大小写
        if(!imageCode.toString().equalsIgnoreCase(dto.getImageCode())){
            //        1. 不一致，返回自定义异常，验证码不正确
            throw new CustomException("图片验证码错误");
        }
        //定义一个变量接受最终验证码
        String resultCode = "";
//        5.根据前端传递的手机号，拼接业务键去redis中查询
        String smsKey = dto.getMobile()+":register";//smsKey-是手机号加业务键
        //smsCode-是Redis里面查询到的短信验证码
        Object smsCode = redisTemplate.opsForValue().get(smsKey);
        if(smsCode != null){
            String[] split = smsCode.toString().split(":");
            String timeStamp = split[1];
            if(System.currentTimeMillis()-Long.parseLong(timeStamp) < (1*60*1000)){
                throw new CustomException("请勿重复发送短信验证码");
            }
            //如果超过一分钟就刷新验证码的时间
            redisTemplate.opsForValue().set(smsKey,smsCode,3,TimeUnit.MINUTES);
            //发送旧的验证码
            resultCode = smsCode.toString().split(":")[0];
        }else{
            //随机生成四位短信验证码
            String newSmsCode = StrUtils.getComplexRandomString(4);
            //在短信验证码后面添加时间戳
            String redisValue = newSmsCode+":"+System.currentTimeMillis();
            //保存到Redis中
            redisTemplate.opsForValue().set(smsKey,redisValue,3,TimeUnit.MINUTES);
            //发送新的验证码
            resultCode = newSmsCode;
        }

//      SendSmsUtil.SendSms(dto.getMobile(),"您好，您的验证码是"+resultCode);
        System.out.println("您好，您的短信验证码是"+resultCode);
    }

    /**
     * 邮箱验证码
     */
    @Override
    public void sendEmailCode(SendSmsDto dto) {
        //        1. 空参数校验
        if(StringUtils.isEmpty(dto.getEmail())){
            throw new CustomException("请输入邮箱号");
        }
        //        2. 判断该邮箱号用户是否已经注册
        User user = userMapper.queryByUserEmail(dto.getEmail());
        if(user != null){
            throw new CustomException("该用户已经注册");
        }

        //定义一个变量接受最终验证码
        String resultCode = "";
//        5.根据前端传递的手机号，拼接业务键去redis中查询
        String emailKey = dto.getEmail()+":register";//smsKey-是手机号加业务键
        //emailCode-是Redis里面查询到的邮箱验证码
        Object emailCode = redisTemplate.opsForValue().get(emailKey);
        if(emailCode != null){
            String[] split = emailCode.toString().split(":");
            String timeStamp = split[1];
            if(System.currentTimeMillis()-Long.parseLong(timeStamp) < (1*60*1000)){
                throw new CustomException("请勿重复发送短信验证码");
            }
            //如果超过一分钟就刷新验证码的时间
            redisTemplate.opsForValue().set(emailKey,emailCode,3,TimeUnit.MINUTES);
            //发送旧的验证码
            resultCode = emailCode.toString().split(":")[0];
        }else{
            //随机生成四位短信验证码
            String newEmailCode = StrUtils.getComplexRandomString(4);
            //在短信验证码后面添加时间戳
            String redisValue = newEmailCode+":"+System.currentTimeMillis();
            //保存到Redis中
            redisTemplate.opsForValue().set(emailKey,redisValue,3,TimeUnit.MINUTES);
            //发送新的验证码
            resultCode = newEmailCode;
        }

//      SendSmsUtil.SendSms(dto.getMobile(),"您好，您的验证码是"+resultCode);
        System.out.println("您好，您的邮箱验证码是"+resultCode);


    }
}
